<template>
  <section style="width:1000px;margin:20px auto" class="contianer">
    <el-row :gutter="40">
      <el-col :span="19">
        <div class="left">
          <div class="title">
            <h3>发表新攻略</h3>
            <p>分享你的个人游记，让更多人看到哦！</p>
          </div>
          <el-form ref="form" :model="form">
            <el-form-item>
              <el-input v-model="form.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <!-- 富文本 -->
            <el-form-item>
              <!-- useCustomImageHandle处理图像上传，而不是使用默认转换为Base64 -->
              <vue-editor
                v-model="form.content"
                :useCustomImageHandler="true"
                @image-added="imgUpload"
                :editorToolbar="customToolbar"
              ></vue-editor>
            </el-form-item>
            <el-form-item label="选择城市">
              <el-col :span="8">
                <el-autocomplete
                  v-model="form.city"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="请搜索游玩城市"
                  @select="handleSelect"
                ></el-autocomplete>
                <!-- <el-input v-model="form.city" placeholder="请搜索游玩城市"></el-input> -->
              </el-col>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit">发布</el-button>&nbsp;或者
              <a href="javacsript:void(0)" class="save" @click="handleClickDraft">保存到草稿</a>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="right">
          草稿箱&nbsp;(0)
          <div class="draft" v-for="(item,index) in $store.state.post.posts" :key="index">
            <div class="draftTilie" @click="handleGetPosts(index)">
              <a href="javascript:viod(0)">{{item.title}}</a>
              <i class="el-icon-edit"></i>
            </div>
            <div class="draftTime">{{item.time}}</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </section>
</template>

<script>
// 引入下载moment插件将时间转换成标准格式
import moment from "moment";
let VueEditor;

if (process.browser) {
  VueEditor = require("vue2-editor").default.VueEditor;
}

export default {
  components: {
    VueEditor,
    moment
  },
  //   mounted(){

  //   },
  data() {
    return {
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image", "code-block"]
      ],
      form: {
        title: "",
        city: "",
        content: ""
      },
      cityList: [] //城市名称列表,
      //   postsDraft:[],//草稿文章
    };
  },
  methods: {
    // 点击提交
    onSubmit() {
      if (this.form.title.trim().length < 0) {
        this.$message.error("标题不能为空");
        return;
      }
      if (this.form.content.trim().length < 0) {
        this.$message.error("内容不能为空");
        return;
      }
      if (this.form.city.trim().length < 0) {
        this.$message.error("城市名称不能为空");
        return;
      }
      if (this.cityList.indexOf(this.form.city) < 0) {
        this.$message.error("请选择正确的城市名称");
        return;
      }
      this.$axios({
        url: "/posts",
        method: "post",
        data: this.form,
        headers: {
          Authorization: `Bearer ${this.$store.state.user.userInfo.token ||
            "NO TOKEN"}`
        }
      }).then(res => {
        // console.log(res.data);
        if (res.data.message == "新增成功") {
          this.form.title = "";
          this.form.city = "";
          this.form.content = "";
        }
      });
    },
    // 富文本图片上传
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      // file 使我们要上传的文件
      // Editor 是我们正在使用的编辑器
      // cursorLocation 这是子组件获取到的当前光标位置
      // restUploader 这是当你处理完了所有数据,应该重置这个上传的组件
      // console.log(file);
      var formData = new FormData();
      formData.append("files", file);
      // console.log(formData)

      //if(formData.length > 0) {
      this.$axios({
        url: "/upload",
        method: "post",
        data: formData
      }).then(res => {
        let url = res.data.map(v => {
          return `${this.$axios.defaults.baseURL}${v.url}`;
        });
        // console.log(url)
        url.forEach(element => {
          Editor.insertEmbed(cursorLocation, "image", element);
        });
        // 有一个必须要做的就是重置上传组件
        resetUploader();
      });
      //}
    },
    // 焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    querySearchAsync(queryString, cb) {
      let arr = [];
      //   console.log(queryString)
      if (!queryString.trim()) {
        return cb(arr);
      }
      this.$axios({
        url: "/airs/city",
        method: "get",
        params: {
          name: queryString
        }
      }).then(res => {
        const { data } = res.data;
        // 下拉提示列表必须要有value字段添加value字段
        arr = data.map(element => {
          return {
            ...element,
            value: element.name
          };
        });
        data.forEach(element => {
          this.cityList.push(element.name);
        });
        // arr是数组每一项要是对象，对象中要有value值
        // cb带的参数是在列表展示数据的每一项的value
        cb(arr);
      });
    },
    // 鼠标选中是触发
    handleSelect(item) {
      //   console.log(item);
      this.form.city = item.value;
    },
    // 添加到本地
    handleClickDraft() {
      let data = new Date();
      let posts = { ...this.form, time: "" };
      posts.time = moment(data).format("YYYY-MM-DD");
      this.$store.commit("post/setLocalStorage", posts);
    },
    //修改草稿箱文章
    handleGetPosts(index) {
      let { posts } = this.$store.state.post;
      this.form.title = posts[0].title;
      this.form.city = posts[0].city;
      this.form.content = posts[0].content;
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  margin: 20px auto;
}
.left {
  .title {
    h3 {
      font-weight: normal;
      font-size: 20px;
      color: #333;
    }
    p {
      font-size: 12px;
      color: #cdcdcd;
      padding: 10px 0;
    }
  }
  .save {
    color: #ffa500;
    &:hover {
      text-decoration: underline solid #ffa500;
    }
  }
}
.right {
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  padding: 10px 10px;
  border-radius: 5px;
  color: #9f9f9f;
  border: 1px solid #e5e5e5;
  .draft {
    margin-top: 10px;
    color: #333;
  }
  .draftTilie {
    &:hover {
      color: #ffa500;
      a {
        text-decoration: underline;
      }
    }
  }
  .draftTime {
    font-size: 14px;
    color: #a69999;
  }
}
</style>